package com.hznc.wcs.flowable.candidate;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.diboot.iam.entity.IamRole;
import com.diboot.iam.entity.IamUser;
import com.diboot.iam.service.IamRoleService;
import com.diboot.iam.service.IamUserService;

import com.hznc.wcs.enums.BpmTaskCandidateStrategyEnum;
import com.hznc.wcs.exception.BusinessException;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色 {@link BpmTaskCandidateStrategy} 实现类
 *
 * @author kyle
 */
@Component
public class BpmTaskCandidateRoleStrategy implements BpmTaskCandidateStrategy {

    @Resource
    private IamRoleService iamRoleService;
    
    @Resource
    private IamUserService iamUserService;

    @Override
    public BpmTaskCandidateStrategyEnum getStrategy() {
        return BpmTaskCandidateStrategyEnum.ROLE;
    }

    @Override
    public void validateParam(String param) {
        String[] roleIdAndRoleNum = StringUtils.split(param, ",");
        List<String> list = Arrays.asList(roleIdAndRoleNum);
        List<String> roleIdList = list.stream().map(item -> item.split("#")[0]).toList();
//        List<String> roleIdList = Arrays.asList(StringUtils.split(param,","));
        for (String roleId : roleIdList){
            LambdaQueryWrapper<IamRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(IamRole::getId,roleId);
            boolean exists = iamRoleService.exists(queryWrapper);
            if (!exists){
                throw new BusinessException("角色不存在");
            }
        }
    }

    @Override
    public Set<String> calculateUsers(DelegateExecution execution, String param) {
        String[] roleIdAndRoleNum = StringUtils.split(param, ",");
        List<String> list = Arrays.asList(roleIdAndRoleNum);
        List<String> roleIdList = list.stream().map(item -> item.split("#")[0]).toList();
//        List<String> roleIdList = Arrays.asList(StringUtils.split(param,","));
        List<IamUser> usersByRoleIds = iamUserService.getUsersByRoleIds(roleIdList);
        return usersByRoleIds.stream().map(IamUser::getId).collect(Collectors.toSet());
    }

}